from rest_framework import viewsets, response, status
from .models import ShippingContainer, Task
from .serializers import ShippingContainerSerializer, TaskSerializer

from celery_client.app import app as celery_app
from celery_client.tasks import on_task_submitted


class ShippingContainerViewSet(viewsets.ModelViewSet):

    queryset = ShippingContainer.objects.all()
    serializer_class = ShippingContainerSerializer # 序列化/反序列化类


class TaskViewSet(viewsets.ModelViewSet):

    queryset = Task.objects.all()

    # [1] -------------------
    serializer_class = TaskSerializer
    # -------------------
    
    def partial_update(self, request, *args, **kwargs):
        """
        处理 PATCH /api/tasks/<id>/ 请求

        根据请求体JSON的内容，做如下操作：

        1. 如果请求体中存在"submit: True"，则立刻提交该计算任务
        2. 否则，按需更新任务本身，比如任务名、任务数据 ...
        """
        # 获取flag： 是否立刻提交任务
        submit_now = request.data.pop('submit', False)

        # 处理操作[2]，一般的任务更新
        super().partial_update(request, *args, **kwargs)
        instance = self.get_object()

        # 继续处理[1]
        if submit_now:
            # 向负责任务状态控制的Celery Worker提交消息
            # "on_task_submitted"定义在本地代码中，所以可以直接import
            # 并调用定义在该函数上的.apply来提交celery task

            on_task_submitted.apply([{
                'task_id': instance.id,
                'tenant_id': request.user.tenant.id
            }]).get()

            instance = self.get_object()

        return response.Response(
            self.get_serializer(instance).data,
            status=status.HTTP_200_OK
        )
